package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.entity.ActivityEntity;
import com.warrior.entity.MatchDetailsEntity;
import com.warrior.entity.TeamEntity;
import com.warrior.service.ActivityService;
import com.warrior.service.MatchDetailsService;
import com.warrior.service.TeamService;
import com.warrior.service.TeamTools;
import com.warrior.util.CModelAndView;
import com.warrior.util.CommonUtils;
import com.warrior.util.DateUtil;
import com.warrior.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 * Created by shawn on 2017/4/25.
 */
@Controller
@RequestMapping("/admin")
public class AdminMatchController {


    @Autowired
    private MatchDetailsService matchDetailsService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private TeamTools teamTools;

    @Autowired
    private TeamService teamService;


    /**
     * 赛事列表
     * @param request req
     * @param response resp
     * @param activityId 活动id
     * @return ModelAndView
     * @throws ProjectException
     */
    @RequestMapping(value = "/matchList",method = RequestMethod.GET)
    public ModelAndView listMatch(HttpServletRequest request, HttpServletResponse response,String activityId){
        ModelAndView mv = new CModelAndView("/admin/game_list_1",request,response);
        List<MatchDetailsEntity> matchDetailsEntities = null;
        try {
            matchDetailsEntities = this.matchDetailsService.findMatchDetailsByActivityId(activityId);
        } catch (ProjectException e) {
            e.printStackTrace();
            mv.addObject("error",e);
        }
        mv.addObject("teamTools",teamTools);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        mv.addObject("activity",activityEntity);
        mv.addObject("matchDetails",matchDetailsEntities);
        return mv;

    }


    /**
     * 添加活动赛事页面
     * @param request req
     * @param response resp
     * @return
     */
    @RequestMapping(value = "/addMatch",method = RequestMethod.GET)
    public ModelAndView addMatch(HttpServletRequest request, HttpServletResponse response,String activityId,String matchId){
        ModelAndView mv = new CModelAndView("admin/game_edit_1",request,response);
        mv.addObject("activityId",activityId);
        if (null!= matchId){
            MatchDetailsEntity matchDetailsEntity = this.matchDetailsService.findMatchDetailById(matchId);
            mv.addObject("match",matchDetailsEntity);
        }
        return mv;
    }

    /**
     * 添加/修改 赛事
     * @param homeScore 主队得分
     * @param visitingScore 客队得分
     * @param matchResult 比赛结果
     * @param matchTime 比赛时间
     * @param activityId 活动id
     * @param homeTeamId 主队id
     * @param visityTeamId 客队id
     * @return
     */
    @RequestMapping(value = "/addMatch",method = RequestMethod.POST)
    @ResponseBody
    public String addMatch(String matchId,String homeScore,String visitingScore,String matchResult,String matchTime,String activityId,String homeTeamId,String visityTeamId){
        MatchDetailsEntity matchDetailsEntity;
        DateUtil dateUtil = new DateUtil();
        if (null==matchId || "".equals(matchId)){
            matchDetailsEntity = new MatchDetailsEntity();
            matchDetailsEntity.setCreatedBy("admin");
            matchDetailsEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
            matchDetailsEntity.setId("MD-"+ UUID.randomUUID().toString().replace("-",""));
        }else {
            matchDetailsEntity = this.matchDetailsService.findMatchDetailById(matchId);
        }

        matchDetailsEntity.setUpdateBy("admin");
        matchDetailsEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        matchDetailsEntity.setHomeScore(CommonUtils.String2Int(homeScore));
        matchDetailsEntity.setVisitingScore(CommonUtils.String2Int(visitingScore));
        matchDetailsEntity.setMatchResult(CommonUtils.String2Int(matchResult));
        matchDetailsEntity.setMatchTime(dateUtil.String2Timestamp(matchTime));
        matchDetailsEntity.setHomeTeamId(homeTeamId);
        matchDetailsEntity.setVisitingTeamId(visityTeamId);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        matchDetailsEntity.setActivityByActiveId(activityEntity);
        this.matchDetailsService.saveNewMatchDetails(matchDetailsEntity);
        //更新队伍积分
        try {
            this.updateTeamScore(homeTeamId, visityTeamId);
        } catch (ProjectException e) {
            e.printStackTrace();
        }
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    @RequestMapping(value = "deleteMatch",method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteMatch(String matchId){
        this.matchDetailsService.deleteMatchDetails(matchId);
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     *计算主客队积分变化
     * @param homeTeamId 主队Id
     * @param visityTeamId 客队Id
     */
    private void updateTeamScore(String homeTeamId,String visityTeamId) throws ProjectException {
        TeamEntity homeTeam = this.teamService.findTeamByTeamId(homeTeamId);
        if (null!=homeTeam.getCaptionId()){
            //找到队伍所有积分赛的比赛
            List<ActivityEntity> activityEntities = this.activityService.findUserAttendActivity(homeTeam.getCaptionId(), 1);
            //找到该活动下的所有比赛
            Integer score = 0;
            for (ActivityEntity activityEntity:activityEntities){
                List<MatchDetailsEntity> matchs = this.matchDetailsService.findMatchDetailsByActivityId(activityEntity.getId());
                for(MatchDetailsEntity matchDetails:matchs){
                    if (matchDetails.getHomeTeamId().equals(homeTeamId)){
                        score = matchDetails.getHomeScore()+score;
                    }else{
                        score = matchDetails.getVisitingScore()+score;
                    }
                }
            }
            if (score!=0){
                Integer teamIntegral =score;
                homeTeam.setTeamIntegral(teamIntegral);
                this.teamService.saveNewTeam(homeTeam);
            }
        }

        TeamEntity visityTeam = this.teamService.findTeamByTeamId(visityTeamId);
        if (null!=visityTeam.getCaptionId()){
            //找到队伍所有积分赛的比赛
            List<ActivityEntity> activityEntities = this.activityService.findUserAttendActivity(visityTeam.getCaptionId(), 1);
            //找到该活动下的所有比赛
            Integer score = 0;
            for (ActivityEntity activityEntity:activityEntities){
                List<MatchDetailsEntity> matchs = this.matchDetailsService.findMatchDetailsByActivityId(activityEntity.getId());
                for(MatchDetailsEntity matchDetails:matchs){
                    if (matchDetails.getHomeTeamId().equals(visityTeamId)){
                        score = matchDetails.getHomeScore()+score;
                    }else{
                        score = matchDetails.getVisitingScore()+score;
                    }
                }
            }
            if (score!=0){
                Integer teamIntegral =score;
                homeTeam.setTeamIntegral(teamIntegral);
                this.teamService.saveNewTeam(visityTeam);
            }
        }



    }


}
